import React, { useEffect, useState } from 'react'
import type { FC } from 'react'
import { UserOutlined } from '@ant-design/icons'
import { Button, Flex, Form, Input, DatePicker } from 'antd'
import dayjs from 'dayjs'
import { useSearchParams } from 'react-router-dom'

interface IProps {
  loadData: (page: number, query: Record<string, any>) => void
}

const SearchUser: FC<IProps> = ({ loadData }) => {
  const [search, setSearch] = useSearchParams()
  let query = Object.fromEntries(search.entries())
  let page = query.page ? Number(query.page) : 1

  const [form] = Form.useForm()

  const onFinish = (values: any) => {
    values = {
      ...values,
      birthday: values.birthday
        ? values.birthday.map((d: dayjs.Dayjs) => d.format('YYYY-MM-DD'))
        : null
    }
    for (let key in values) {
      // delete删除对象中的属性，在ts中此属性的类型一定要有可选类型,为了方便可以用any
      if (!values[key]) delete values[key]
      if (Array.isArray(values[key]) && values[key].length == 0) {
        delete values[key]
      }
      // 做此步骤就是为了防止后端对于search字符串中相当字段名它不会获取的一种处理方案
      if (values[key] && key == 'birthday') {
        values['start'] = values[key][0]
        values['end'] = values[key][1]
        delete values[key]
      }
    }
    setSearch({ ...query, ...values })
    loadData(1, values)
  }

  return (
    <div className="user-search-box">
      <Form
        form={form}
        layout="inline"
        initialValues={{
          username: search.get('username') ?? '',
          realname: search.get('realname') ?? '',
          birthday: search.get('start')
            ? [dayjs(search.get('start')), dayjs(search.get('end'))]
            : []
        }}
        onFinish={onFinish}
      >
        <Form.Item label="账号" name="username">
          <Input prefix={<UserOutlined />} placeholder="请输入搜索账号名称" />
        </Form.Item>
        <Form.Item label="姓名" name="realname">
          <Input prefix={<UserOutlined />} placeholder="请输入搜索姓名" />
        </Form.Item>
        <Form.Item label="生日" name="birthday">
          <DatePicker.RangePicker
            minDate={dayjs('2004-08-01', 'YYYY-MM-DD')}
            maxDate={dayjs('2024-03-31', 'YYYY-MM-DD')}
          />
        </Form.Item>
        <Form.Item>
          <Flex gap="small">
            <Button type="primary" htmlType="submit">
              搜索一下
            </Button>
            <Button
              onClick={() => {
                form.resetFields()
              }}
            >
              重置表单
            </Button>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  )
}

export default SearchUser
